﻿using System.Text;
using System.Text.Json;
using MQTTEntity;
using MQTTnet;
using MQTTnet.Extensions.TopicTemplate;

namespace MQTTSubscriber
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await Handle_Received_Application_Message();
        }
        public static async Task Handle_Received_Application_Message()
        {

            var mqttFactory = new MqttClientFactory();

            using (var mqttClient = mqttFactory.CreateMqttClient())
            {
                var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").Build();
                mqttClient.ApplicationMessageReceivedAsync += e =>
                {
                    Message<string> message = MessageParser.Parse<string>(e.ApplicationMessage.Payload.First.Span.ToArray());
                    Console.WriteLine($"接收到消息:clientid:{e.ClientId},topic:{e.ApplicationMessage.Topic},message:{message.Data}");
                    return Task.CompletedTask;
                };

                await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

                var mqttSubscribeOptions = mqttFactory.
                    CreateSubscribeOptionsBuilder()
                    .WithTopicFilter("mytopic")
                    .Build();

                await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);

                Console.WriteLine("MQTT客户端成功订阅主题:mytopic......");

                Console.WriteLine("按下任意键退出......");
                Console.ReadLine();
                var mqttUnSubscribeOptions = mqttFactory.
                    CreateUnsubscribeOptionsBuilder()
                    .WithTopicFilter("mytopic")
                    .Build();
                //取消订阅
                await mqttClient.UnsubscribeAsync(mqttUnSubscribeOptions);
                Console.ReadLine();
            }
        }
    }
}
